<template>
    <div>
        <Dialog v-model="dialogVisible1" title="导入笔试成绩" width="420">
            <div class="message_p">
                <el-form ref="ruleFormRef" :model="state.form" :rules="rules" label-width="120px" label-position="top">
                    <el-form-item label="职位" prop="recruitmentPositionId">
                        <el-select v-model="state.form.recruitmentPositionId" clearable placeholder="请选择职位"
                            style="width: 100%">
                            <el-option v-for="item in state.positionOptions" :key="item.id" :label="item.positionName"
                                :value="item.id" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="成绩合格分数" prop="">
                        <el-input-number min="0" style="width: 100%;" v-model="state.form.passingGrade" placeholder="成绩合格分数" />
                    </el-form-item>
                    <el-form-item label="上传文件" prop="fileList">
                        <div class="flex aifs jcsb" style="width:100%">
                            <el-upload v-model:file-list="state.form.fileList" :auto-upload="false" limit="1"
                                :on-change="handleAvatarSuccess" class="upload-demo" multiple>
                                <el-button type="primary">上传文件</el-button>
                                <template #tip>
                                    <div class="el-upload__tip">
                                        单个文件大小不超过10M，最多上传1个，支持Excel格式
                                    </div>
                                </template>
                            </el-upload>
                        </div>
                    </el-form-item>
                    <el-button link type="primary" class="" @click="down">下载标准导入模板</el-button>
                    <div class="flex jcfe aic" style="width: 100%;">
                        <el-button @click="DialogClose()">取消</el-button>
                        <el-button type="primary" @click="submitForm(ruleFormRef)">确定</el-button>
                    </div>
                </el-form>
            </div>
        </Dialog>
    </div>
</template>
<script lang="ts" setup>
import { positionListAlls } from "@/api/recruit/index"
import { downloadWrittenExaminationScoreTemplate } from "@/api/home/index"
import type { FormInstance, FormRules } from 'element-plus'
import { ref, reactive } from 'vue'
import { Dialog } from '@/components/Dialog'
import { ElButton, ElMessage } from 'element-plus'
import type { UploadProps, UploadUserFile } from 'element-plus'
const dialogVisible1 = ref(false)
const emit = defineEmits(['penFileClick'])
const props = defineProps({
    penData: {
        type: Object,
        default: () => {
            return {}
        }
    }

})
interface RuleForm {
    recruitmentPositionId: string
    passingGrade: number
    fileList: string[]
}
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules<RuleForm>>({
    recruitmentPositionId: [{ required: true, message: '请选择职位', trigger: 'blur' }],
    passingGrade: [{ required: true, message: '请填写成绩合格分数', trigger: 'blur' }],
    fileList: [{ type: "array", required: true, message: '请上传文件', trigger: 'blur' }],

})
const state = reactive({
    form: {
        passingGrade: "",
        recruitmentPositionId: "",
        fileList: []
    } as any,

    fileList: [],
    positionOptions: [] as any,
})

const down = () => {
    downloadWrittenExaminationScoreTemplate().then(res => {
        const userAgent = navigator.userAgent;
        console.log(userAgent);
        const isIE = userAgent.indexOf('MSIE') !== -1 || userAgent.indexOf('Trident') !== -1;
        const isEdge = userAgent.indexOf('Edge') !== -1 || userAgent.indexOf('Edg') !== -1;
        const isFirefox = userAgent.indexOf('Firefox') !== -1;
        const isChrome = userAgent.indexOf('Chrome') !== -1 && userAgent.indexOf('Edge') === -1 && userAgent.indexOf('Edg') === -1;
        const isSafari = userAgent.indexOf('Safari') !== -1 && userAgent.indexOf('Chrome') === -1;
        // if (isIE) {
        //     console.log('Internet Explorer detected');
        // } else if (isEdge) {
        //     console.log('Microsoft Edge detected');

        // } else if (isFirefox) {
        //     console.log('Mozilla Firefox detected');
        // } else if (isChrome) {
        //     console.log('Google Chrome detected');
        //     console.log("下载", res);
        //     const link = document.createElement('a');
        //     link.href = res.data;
        //     link.setAttribute('download', res.data);
        //     link.click();
        // } else if (isSafari) {
        //     console.log('Safari detected');
        // } else {
        //     console.log('Unknown browser');

        // }
        if (isEdge) {
            console.log(res.data);
            window.open(res.data);
            return
            const link = document.createElement('a')
            link.href = res.data;

            link.download = res.data
            document.body.appendChild(link)
            link.click()
            setTimeout(() => {
                window.URL.revokeObjectURL(href)
                document.body.removeChild(link)
            }, 0)
        } else {
            console.log("下载", res);
            const link = document.createElement('a');
            link.href = res.data;
            link.setAttribute('download', res.data);
            link.click();
        }

    })

}

const handleAvatarSuccess: UploadProps['onChange'] = (
    response: any,
    uploadFile
) => {
    if (response.raw.type != 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
        ElMessage.error('格式有误! 仅支持xlsx格式!')
        state.form.fileList.pop()
        return
    } else if (response.raw.type / 1024 / 1024 > 10) {
        ElMessage.error('文件大小不超过10MB!')
        state.form.fileList.pop()
        return
    }
    state.form.fileList = uploadFile
    console.log("文件变换", response, uploadFile, state.form.fileList);


    // state.ruleForm.ossIds

}
const DialogOpen = () => {
    positionListAllApi()
    state.form = {}
    dialogVisible1.value = true
}
const DialogClose = () => {
    dialogVisible1.value = false
}

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            // const aBlob = new Blob([state.form.fileList[0].raw], { type: state.form.fileList[0].raw.type })
            // console.log(aBlob)
            let obj = {
                passingGrade: state.form.passingGrade,
                recruitmentPositionId: state.form.recruitmentPositionId,
                "file": state.form.fileList[0].raw
            }
            emit('penFileClick', obj)
        } else {
            console.log('error submit!', fields)
        }
    })
}
// 暴露方法
defineExpose({
    DialogOpen,
    DialogClose
})


const positionListAllApi = async () => {
    await positionListAlls({
        searchValue: "",
        statusLe: 3,
        statusGe: 3
    }).then(res => {
        // console.log("全部职位", res);
        state.positionOptions = res.data
    })
}

</script>
<style lang="less">
.el-dialog__header {
    padding: 10px;
    border-bottom: 1px solid #D8D8D8;
}

.el-dialog__body {
    padding: 20px;
}
</style>
<style lang="less" scoped>
.message_p {
    padding: 0px 10px 20px 10px;
}

.el-button {
    margin-top: 20px;
    width: 134px;
    height: 40px;
}
</style>